package com.shell.mystudent;

import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private EditText editNum;
    private EditText editName;
    private EditText editScore;
    private Button btnInsert;
    private Button btnSelect;
    private Button btnDelete;
    private Button btnUpdate;
    private TextView editShow;

    private SQLiteDatabase db;

    ContentResolver resolver;
    ContentValues values;
    Uri uri;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
    }

    public void init() {
        editNum = findViewById(R.id.edit_num);
        editName = findViewById(R.id.edit_name);
        editScore = findViewById(R.id.edit_score);
        btnInsert = findViewById(R.id.btn_insert);
        btnSelect = findViewById(R.id.btn_select);
        btnDelete = findViewById(R.id.btn_delete);
        btnUpdate = findViewById(R.id.btn_update);
        editShow = findViewById(R.id.edit_show);

        btnInsert.setOnClickListener(this);
        btnSelect.setOnClickListener(this);
        btnDelete.setOnClickListener(this);
        btnUpdate.setOnClickListener(this);
        editNum.setOnClickListener(this);//点击“学号”编辑框
        editName.setOnClickListener(this);//点击“姓名”编辑框

    }

    @Override
    public void onClick(View v) {
        resolver = getContentResolver();
        values = new ContentValues();
        uri = DBUtil.CONTENT_URI;//多个学生

        String num = editNum.getText().toString();//获取学号
        String name = editName.getText().toString();//获取姓名
        switch (v.getId()) {
            case R.id.btn_insert:
                clickBtnInsert(resolver, values, uri);//点击“添加”
                break;
            case R.id.btn_select:
                clickBtnSelect(resolver, uri);//点击“查询”
                break;
            case R.id.btn_delete:
                clickBtnDelete(resolver, uri, "_id=?", new String[]{num});//点击”删除“
                break;
            case R.id.btn_update:
                clickBtnUpdate(resolver,uri,values,"_id=?",new String[]{num});//点击“修改”
                break;
            case R.id.edit_num:
                clickEditNum();//点击“学号”编辑框
                break;
            case R.id.edit_name:
                clickEditName();//点击“姓名”编辑框
                break;
        }

    }

    //点击“添加”
    public void clickBtnInsert(ContentResolver resolver, ContentValues values, Uri uri) {

        String num = editNum.getText().toString();//获取学号
        String name = editName.getText().toString();//获取姓名
        String score = editScore.getText().toString();//获取成绩
        if (num.isEmpty()) {
            Toast.makeText(this, "学号不能为空", Toast.LENGTH_LONG).show();
            return;
        }
        if (name.isEmpty()) {
            Toast.makeText(this, "姓名不能为空", Toast.LENGTH_LONG).show();
            return;
        }
        if (score.isEmpty()) {
            Toast.makeText(this, "成绩不能为空", Toast.LENGTH_LONG).show();
            return;
        }
        values.put(DBUtil.STU_ID, num);//列名，值
        values.put(DBUtil.STU_NAME, name);
        values.put(DBUtil.STU_SCORE, score);
        resolver.insert(uri, values);

        editName.setText("");
        editNum.setText("");
        editScore.setText("");
        clickBtnSelect(resolver, uri);//查询展示一下结果
    }

    @SuppressLint("Recycle")
    //点击“查询”
    public void clickBtnSelect(ContentResolver resolver, Uri uri) {
        Cursor cursor = resolver.query(uri, null, null, null, null);
        if (cursor.getCount() <= 0) {
            editShow.setText("没有查询结果");
        } else {
            editShow.setText("执行结果如下所示：\n学号  姓名  成绩 \n");
            while (cursor.moveToNext()) {
                String num = cursor.getString(0);
                String name = cursor.getString(1);
                String score = cursor.getString(2);
                editShow.append(num + "  ");
                editShow.append(name + "  ");
                editShow.append(score + "\n");
            }
        }
    }

    //点击“删除”
    public void clickBtnDelete(ContentResolver resolver, Uri uri, String selection, String[] selectionArgs) {
        String num = editNum.getText().toString();//获取学号
        if (num.isEmpty()) {
            Toast.makeText(this, "请输入学号！", Toast.LENGTH_LONG).show();
        } else {
            resolver.delete(uri, selection, selectionArgs);//按学号删除，操作对象是单个学生
            clickBtnSelect(resolver, uri);//查询一下结果
        }
    }

    //点击“修改”
    static boolean isUpdate = true; //判断“修改”按钮是否被点击过

    public void clickBtnUpdate(ContentResolver resolver,Uri uri, ContentValues values, String selection,
                               String[] selectionArgs) {
        if (isUpdate) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this); //新建对话框
            builder.setIcon(R.mipmap.ic_launcher);//设置图标
            builder.setTitle("请输入想修改的学号");
            View view = LayoutInflater.from(this).inflate(R.layout.layout_student_update, null);//从布局填充器填充
            builder.setView(view); //放置视图
            final EditText num = view.findViewById(R.id.deleteByNum);//获取自定义对话框中的“学号”

            builder.setPositiveButton("修改信息", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    int number = Integer.parseInt(num.getText().toString());//获取输入的学号
                    if (num.getText().toString().isEmpty()) {
                        dialog.dismiss();
                        return;
                    }

                    //表名，列名，条件，数组依次填充?，分组方式，接收having条件，排序方式
                    Cursor cursor = resolver.query(uri,null,"_id=?",new String[]{number+""},null);
                    if (cursor.getCount() <= 0) {
                        editShow.setText("没有查询结果");
                    } else {
                        //将查询结果填充到当前页面
                        while (cursor.moveToNext()) {
                            String num = cursor.getString(0);
                            String name = cursor.getString(1);
                            String score = cursor.getString(2);
                            editNum.setText(num);
                            editNum.setEnabled(false);//禁止编辑学号
                            editName.setText(name);
                            editScore.setText(score);
                            dialog.dismiss();//隐藏对话框
                            isUpdate = false; //改变“修改”按钮状态标志
                        }
                    }
                }
            });

            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();//隐藏对话框
                }
            });
            builder.show();//显示当前自定义对话框
        }
        if (!isUpdate) {//按照页面上的信息执行修改
            String num = editNum.getText().toString();//获取学号
            String name = editName.getText().toString();//获取姓名
            String score = editScore.getText().toString();//获取成绩

            if (num.isEmpty()) {
                Toast.makeText(this, "学号不能为空", Toast.LENGTH_LONG).show();
                editNum.setEnabled(true);
                return;
            }
            if (name.isEmpty()) {
                Toast.makeText(this, "姓名不能为空", Toast.LENGTH_LONG).show();
                editNum.setEnabled(true);
                return;
            }
            if (score.isEmpty()) {
                Toast.makeText(this, "成绩不能为空", Toast.LENGTH_LONG).show();
                editNum.setEnabled(true);
                return;
            }
            values.put(DBUtil.STU_NAME, name);
            values.put(DBUtil.STU_SCORE, score);
            //表名，值，条件，填充前面的占位符
            resolver.update(uri,values,selection,selectionArgs);
            clickBtnSelect(resolver,uri); //调用查询方法，便于观察结果
            isUpdate = true;
            editNum.setEnabled(true);
            editName.setText("");
            editNum.setText("");
            editScore.setText("");
        }
    }

    //点击“学号”编辑框
    public void clickEditNum() {
        editNum.setText("");
    }

    //点击“姓名”编辑框
    public void clickEditName() {
        editName.setText("");
    }
}